<template>
  <div class="home-pc-container c-flex-x-between">
    <div>
      <!-- 主内容 -->
      <div class="main">
        我是case页面
        <!-- 详情部分 -->
        <div v-if="pageShow">
          <van-list
            class="news-list"
            v-if="newsList.length"
            key="news"
            ref="vanList"
            v-model="loading"
            :finished="finished"
            finished-text=""
            @load="onLoad('push')"
            :offset="100"
          >
            <div
              class="item-node"
              :class="'item-' + item.id"
              v-for="(item, index) in newsList"
              :key="index"
            >
              <Item
                ref="item"
                :id="item.id"
                :key="'newsList-' + index"
                :item.sync="item"
                :index="index"
                type="groupDetail"
                @btnControl="btnControl"
              />

              <div class="line-1px"></div>
            </div>

            <div class="finashed" v-if="finished"></div>
            <div class="news-space"></div>
          </van-list>

          <NoData class="no-data" v-else>
            <p>还没有发布过任何内容呢</p>
          </NoData>
        </div>

        <div class="skeleton" v-else>
          <van-skeleton
            v-for="(item, index) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
            :key="index"
            title
            avatar
            :row="3"
          />
        </div>
      </div>
    </div>

    <div class="info">
      <Introduce
        :data="{
          title1: userInfo.name || '',
          title2: userInfo.orgName || '',
        }"
      ></Introduce>

      <div class="line"></div>

      <div class="info_counts c-flex-y-center">
        <Counts
          :data="[
            {
              num: userInfoAll ? userInfoAll.data.community.answerCount : '0',
              text: '回答数',
            },
            {
              num: userInfoAll ? userInfoAll.data.community.likedCount : '0',
              text: '被赞数',
            },
            {
              num: '等接口',
              text: '提问数',
            },
          ]"
        ></Counts>

        <div class="btn1">
          <Btn1 :text="'发布案例'"></Btn1>
        </div>
      </div>
    </div>

    <router-view @publish="publish"></router-view>
  </div>
</template>

<script>
// vuex
import { mapMutations, mapActions, mapState, mapGetters } from "vuex";

// 工具函数
import { suffix_v2, stopScroll, goBack, debounce } from "@/utils";
import { failDialog, clearToast, toast, loading } from "@/utils/vantApi";

// 接口
import {
  getTopicAndAnswerList,
  getFollowingAnswerList,
} from "@/api/pages/home_v2/home_v2.js";
import { match, create } from "@/api/pages/home_v2/ask/ask.js";
import {
  // info,
  // detail,
  // like,
  // collect,
  answerCreate,
  focusTopic,
  // answerGetList,
  // getRecommendedUserList,
  // inviteUser,
} from "@/api/pages/community/sqDetail.js";

// 组件
import Item from "./components/Item.vue";
import Introduce from "./components/components/Introduce.vue";
import Counts from "./components/components/Counts.vue";
import Btn1 from "./components/components_btns/Btn1.vue";
import Bottom from "./components/components/Bottom";
import Avator from "./components/components/Avator";
import AvatorV2 from "./components/components/Avator_v2";
import Btn2 from "./components/components_btns/Btn2";
import InviteAnswer from "@_pc/views/home/components/components/InviteAnswer.vue";
import NoData from "@_pc/components/NoData.vue";

export default {
  name: "HomePc",
  data() {
    return {
      that: null,

      listShow: false, // tabs下方列表数据标识
      pageShow: false,

      data: {}, // 当前小组信息

      swiperLoading: false, // swiper的loading样式

      // 列表数据系列---
      newsList: [],
      page: 1,
      pagesize: 20, // 固定每页展示20个
      loading: false,
      finished: false,
      limit: true,
      // ---

      // 邀请弹窗
      inviteShow: false,
      currentData: {}, // 当前选中的item数据
    };
  },
  props: {},
  mixins: [],
  components: {
    Item,
    Introduce,
    Counts,
    Btn1,
    Bottom,
    Avator,
    AvatorV2,
    Btn2,
    InviteAnswer,
    NoData,
  },
  computed: {
    // 动态计算vuex属性
    ...mapState(["userInfo", "userInfoAll"]),
  },
  filters: {
    suffix(value) {
      return suffix_v2(value, 120);
    },
  },
  watch: {
    // userInfoAll: {
    //   handler(newValue, oldValue) {
    //     console.log(12345);
    //     console.log(newValue);
    //   },
    //   immediate: true,
    // },
  },
  // vue-router路由守卫，前置
  beforeRouteUpdate(to, from, next) {
    next();
  },
  // 销毁组件时执行
  destroyed() {},
  created() {},
  mounted() {
    this.that = this;

    this.start();
  },
  methods: {
    start() {
      Promise.all([this.onLoad()]).then(() => {
        setTimeout(() => {
          this.listShow = true;
        }, 200);
      });
    },

    // 动态数据加载
    onLoad(type) {
      return new Promise((resolve, reject) => {
        if (!this.limit) return;
        this.limit = false;

        let groupId = this.groupId ? this.groupId : "";

        let json = {
          group_id: groupId,
          page: this.page,
          page_size: this.pagesize,
        };
        getTopicAndAnswerList(json)
          .then((res) => {
            // console.log(res);
            // return false;

            this.pageShow = true;

            let data = res.data && res.data.list ? res.data.list : [];
            // this.handleData(data);

            // 没有更多
            if (!data.length) {
              this.finished = true;
            }

            // 延迟1s钟渲染页面，目的是避免接口过快引起页面闪一下.
            this.delay(type).then(() => {
              // setTimeout(() => {
              //   this.listShow = true;
              // }, 200);

              if (type == "push") {
                this.newsList = this.newsList.concat(data);
              } else {
                this.newsList = data;
              }

              this.page++;

              // 定位后，恢复下拉加载和滚动加载.
              this.loading = false;
            });
          })
          .finally(() => {
            this.limit = true;

            resolve();
          });
      });
    },

    delay(type) {
      return new Promise((resolve, reject) => {
        if (type == "push") {
          setTimeout(() => {
            resolve();
          }, 500);
        } else {
          resolve();
        }
      });
    },

    btnControl(type, item) {
      // console.log(item);
      // return false;

      // 暂存当前点击数据
      this.currentData = item;

      if (type === "goDetail") {
        let name = "";
        switch (item.entity_type) {
          case 3:
            name = "homeAnswerDetail_pc";
            break; // 回答详情
          case 2:
            name = "homeTopicDetail_pc";
            break; // 问题详情
          default:
            name = "";
            break;
        }

        this.pushPage({
          name: name,
          query: {
            id: this.currentData.id,
          },
        });
      } else if (type === "writeAnswer") {
        // 写回答按钮

        this.pushPage({
          name: "writeAnswer_pc",
          params: {
            dataOrigin: item,
          },
        });
      } else if (type === "invite") {
        // 邀请回答按钮
        this.inviteShow = true;
      } else if (type === "likeQuestion") {
        // 关注问题回答按钮
        this.followFunc(item);
      }
    },
    // 关注操作
    followFunc() {
      let operate = ""; // 关注参数
      let id = this.currentData.id; // 话题id

      // if (this.topic.focused == 1) {
      //   toast("取消成功");
      //   this.topic.focused = false;

      //   operate = 2;
      // } else {
      //   toast("关注成功");
      //   this.topic.focused = true;

      //   operate = 1;
      // }
      operate = 1;

      // 强制更新data渲染
      this.$forceUpdate();

      let json = {
        id,
        operate: operate,
      };
      focusTopic(json).then((res) => {
        console.log(res);
      });
    },
    publish(data) {
      console.log(123);
      console.log(data);

      stopScroll(false);

      this.reStartList();

      // let topicId = this.currentData.id;
      // let content = data.html;

      // if (content === "<p><br></p>") {
      //   failDialog("你一个字都没写呢");
      //   return false;
      // }

      // // loading(true);

      // let json = {
      //   topicid: topicId,
      //   content: content,
      // };
      // // console.log(json)
      // // return false
      // answerCreate(json)
      //   .then((data) => {
      //     console.log(data);

      //     // this.show = false

      //     stopScroll(false);

      //     this.reStartList();

      //     goBack();
      //   })
      //   .catch((error) => {
      //     failDialog(error);
      //     setTimeout(() => {
      //       clearToast();
      //     }, 1500);
      //   });
    },
    reStartList() {
      // this.list = []

      this.page = 1;
      this.loading = true; // 避免翻页重复加载
      this.finished = false; // 加载完成标识(最后一页)

      this.start();
    },
  },
};
</script>

<style lang="scss" scoped>
.home-pc-container {
  position: relative;
  width: 1200px;
  min-height: calc(100vh - 80px);
  margin: 0 auto;
  background: #f5f6f7;
  align-items: flex-start;

  .main {
    width: 845px;
    // height: 500px;
    background-color: #fff;
  }

  .info {
    position: sticky;
    box-sizing: border-box;
    top: 80px;
    width: 339px;
    // height: 264px;
    padding: 24px 20px;
    background: #fff;

    .line {
      width: 299px;
      height: 1px;
      background: #eff0f1;
      margin: 20px 0;
    }

    .info_counts {
      .btn1 {
        margin-top: 16px;
      }
    }
  }
}
</style>
